import type { AnyAction, Dispatch } from 'redux'
import type { Users } from '../api/model/userSearchTypes'
import { reqSearchUsers } from '../api/userSearch'
/* 
管理用户搜索模块相关数据的redux模块
1. action creator
2. reducer
*/
// 请求中的同步action
const requestingAction = () => ({type: 'REQUESTING'})
// 请求成功的同步action
const reqSuccessAction = (users: Users) => ({type: 'REQ_SUCCESS', payload: users})
// 请求失败的同步action
const reqErrorAction = (errorMsg: string) => ({type: 'REQ_ERROR', payload: errorMsg})



// 搜索的异步action
export const searchAsyncAction = (searchName: string) => {
  return async (dispatch: Dispatch) => {  // store.dispatch
    // 发请求前: 分发请求中的同步action
    dispatch(requestingAction())
    try {
      // 发送ajax请求
      const {items} = await reqSearchUsers(searchName)
      // 请求成功: 分发请求成功的同步action
      dispatch(reqSuccessAction(items))
    } catch (error: any) {  // tey...catch的error总是指定为any类型
      // 请求失败: 分发请求失败的同步action
      dispatch(reqErrorAction(`请求失败: ${error.message}`))
    }
  }
}

// 状态类型
interface UserSearchState {
  firstView: boolean;
	loading: boolean;
	errorMsg: string;
	users: Users
}

const initState: UserSearchState = {
  firstView: true,
	loading: false,
	errorMsg: '',
	users: []
}
export default function userSearchReducer(state=initState, action: AnyAction) {
  console.log('userSearchReducer', state, action)
  switch (action.type) {
    case 'REQUESTING':
      return {
        firstView: false,
        loading: true,
        errorMsg: '',
	      users: []
      }
    case 'REQ_SUCCESS':
      return {
        // firstView: false,
        // errorMsg: '',
        ...state,
        loading: false,
        users: action.payload as Users
      }
    case 'REQ_ERROR':
      return {
        ...state,
        loading: false,
        errorMsg: action.payload as string
      }
    default:
      return state
  }
}